package com.kkb.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kkb.mapper.TeamMapper;
import com.kkb.pojo.Team;
import com.kkb.pojo.TeamExample;
import com.kkb.vo.QueryVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class TeamService {
    @Resource
    private TeamMapper teamMapper;

    @Transactional(propagation = Propagation.REQUIRED, readOnly = true)
    public PageInfo<Team> queryByPage(Integer pageNum, Integer pageSize, QueryVO vo) {
        TeamExample example = new TeamExample();
        TeamExample.Criteria criteria = example.createCriteria();
        if (vo != null) {
            if (vo.getTeamName() != null && !"".equals(vo.getTeamName().trim())) {
                criteria.andTeamNameLike("%" + vo.getTeamName() + "%");
            }
            if (vo.getChineseName() != null && !"".equals(vo.getChineseName().trim())) {
                criteria.andChineseNameLike("%" + vo.getChineseName() + "%");
            }
            if (vo.getCoachName() != null && !"".equals(vo.getCoachName().trim())) {
                criteria.andCoachLike("%" + vo.getCoachName() + "%");
            }
            if (vo.getBeginTime() != null) {
                criteria.andCreateTimeGreaterThanOrEqualTo(vo.getBeginTime());
            }
            if (vo.getEndTime() != null) {
                criteria.andCreateTimeLessThanOrEqualTo(vo.getEndTime());
            }
            if (vo.getArea() != null && vo.getArea() != -1) {
                criteria.andAreaEqualTo(vo.getArea());
            }
        }
        PageHelper.startPage(pageNum, pageSize);
        List<Team> teamList = teamMapper.selectByExample(example);
        return new PageInfo<>(teamList);
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public int addTeam(Team team) {
        return teamMapper.insertSelective(team);
    }

    @Transactional(propagation = Propagation.REQUIRED, readOnly = true)
    public Team findById(int teamId) {
        return teamMapper.selectByPrimaryKey(teamId);
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public int updateTeam(Team team) {
        return teamMapper.updateByPrimaryKeySelective(team);
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public int deleteTeam(int teamId) {
        Team team = teamMapper.selectByPrimaryKey(teamId);
        team.setIsDel(1);
        return teamMapper.updateByPrimaryKeySelective(team);
    }
}
